<template>
  <div class="container">
    <div class="app-container">
      <!-- props可以修改指定的标签名 -->
      <el-tree :data="list" default-expand-all :props="{label:'name'}" :expand-on-click-node="false">
        <template #default="{data}">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col style="width:140px;">
              <span style="margin:0px 20px;">管理员</span>
              <el-dropdown @command="fn($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>

          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 引入弹出层组件 -->
    <!-- 父传子去打开弹出层 -->
    <!-- 父传子visible 绑定visible给dialog   $event在组件子传父的值接收  @close="visible = $event"点击x关闭弹出层-->
    <!-- <add-dsp :visible="visible" @close="visible = $event" /> -->
    <add-dsp ref="depRef" :visible.sync="visible" :pid="pid" @onSuccess="onLoad" />
  </div>
</template>
<script>
// 定义pid，新增部门 点击新增的时候把id传给定义的pid 父传子，传给子组件 发请求
import { delDepApi, getDespAPi } from '@/api/department'
import { list2Tree } from '@/utils'
import addDsp from './components/add-dsp.vue'
export default {
  name: 'Department',
  components: { addDsp },
  data() {
    return {
      list: [],
      // 定义弹出层
      visible: false,
      pid: null
    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    // 获取详情数据
    async onLoad() {
      const res = await getDespAPi()
      // console.log(res.data)
      // 转换成树状,传给空数组渲染页面
      const tree = list2Tree(res.data, 0)
      // console.log(tree)
      this.list = tree
    },
    fn(type, id) {
      if (type === 'add') {
        // alert('add')
        this.visible = true
        this.pid = id
      } else if (type === 'edit') {
        // 点击编辑回填数据  封装api 在子组件定义一个方法把请求回来的数据传给定义的表单数据  在父组件点击后当前点击的id传给子组件定义的方法 实现回填数据
        this.visible = true
        // 提前传入id 防止闪烁
        this.$refs.depRef.formData.id = id
        // this.$refs.depRef
        this.$refs.depRef.onEdit(id)
      } else {
        // 封装api 提示用户二次确认 调用接口 提示用户删除成功 关闭 刷新
        this.$confirm('您确定要删除吗？').then(async() => {
          await delDepApi(id)
          this.onLoad()
          this.$message.success('删除成功')
        })
      }
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
